package com.euro.video.phone.servlet;

import java.io.BufferedOutputStream;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.euro.video.phone.services.ArticleService;
import com.euro.video.phone.services.PubliciteService;

@Component
public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Autowired
	private ArticleService artService;
	@Autowired
	private PubliciteService pubService;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
				config.getServletContext());
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Get IDs from request.
		String id = request.getParameter("id");
		String tab = request.getParameter("tab");
		// Check if ID is supplied to the request.
		if (id == null || tab == null) {
			return;
		}
		// Lookup Image by id in database.
		byte[] image = null;
		try {
			if (tab.equals("art")) {
				image = artService.getImage(id);
			} else {
				image = pubService.getImage(id);
			}
		} catch (Exception e) {
			throw new IOException(e);
		}
		// Check if image is actually retrieved from database.
		if (image == null) {
			return;
		}
		// Init servlet response.
		response.reset();
		response.setBufferSize(image.length);
		response.setContentType("image/png");
		response.setHeader("Content-Length", String.valueOf(image.length));
		response.setHeader("Content-Disposition", "inline; filename=\"" + id
				+ "\"");
		// Prepare streams.
		BufferedOutputStream output = null;
		try {
			output = new BufferedOutputStream(response.getOutputStream(),
					image.length);
			// Write file contents to response.
			output.write(image);
		} finally {
			// Gently close streams.
			output.close();
		}
	}
}